package com.laundry.service;

import com.laundry.dto.UserResponse;
import com.laundry.entity.User;
import com.laundry.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    public UserResponse getCurrentUserProfile() {
        User user = getCurrentUser();
        return UserResponse.fromUser(user);
    }
    
    @Transactional
    public UserResponse updateUserProfile(Map<String, Object> updates) {
        User user = getCurrentUser();
        
        if (updates.containsKey("nickname")) {
            user.setNickname((String) updates.get("nickname"));
        }
        
        if (updates.containsKey("realName")) {
            user.setRealName((String) updates.get("realName"));
        }
        
        if (updates.containsKey("gender")) {
            String genderStr = (String) updates.get("gender");
            if (genderStr != null) {
                user.setGender(User.Gender.valueOf(genderStr.toUpperCase()));
            }
        }
        
        if (updates.containsKey("avatar")) {
            user.setAvatar((String) updates.get("avatar"));
        }
        
        User savedUser = userRepository.save(user);
        return UserResponse.fromUser(savedUser);
    }
    
    @Transactional
    public void changePassword(String oldPassword, String newPassword) {
        User user = getCurrentUser();
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码不正确");
        }
        
        // 设置新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
    }
    
    @Transactional
    public UserResponse updateMobile(String mobile, String verificationCode) {
        // 这里应该验证短信验证码，暂时跳过
        User user = getCurrentUser();
        
        // 检查手机号是否已被使用
        if (userRepository.existsByMobile(mobile)) {
            throw new RuntimeException("手机号已被使用");
        }
        
        user.setMobile(mobile);
        user.setMobileVerified(true);
        User savedUser = userRepository.save(user);
        
        return UserResponse.fromUser(savedUser);
    }
    
    @Transactional
    public UserResponse updateEmail(String email, String verificationCode) {
        // 这里应该验证邮箱验证码，暂时跳过
        User user = getCurrentUser();
        
        // 检查邮箱是否已被使用
        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("邮箱已被使用");
        }
        
        user.setEmail(email);
        user.setEmailVerified(true);
        User savedUser = userRepository.save(user);
        
        return UserResponse.fromUser(savedUser);
    }
    
    @Transactional
    public UserResponse verifyRealName(String realName, String idCard) {
        User user = getCurrentUser();
        
        // 这里应该调用实名认证接口，暂时直接设置
        user.setRealName(realName);
        user.setIdCard(idCard);
        user.setRealNameVerified(true);
        User savedUser = userRepository.save(user);
        
        return UserResponse.fromUser(savedUser);
    }
    
    private User getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return userRepository.findByUsernameOrEmailOrMobile(username, username, username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
}
